package org.easy.excel.support.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.easy.excel.support.parse.source.ExportLabelSource;

import java.util.List;

/**
 * Excel单元格宽度样式设置拦截器
 *
 * @author 李坤
 * @date 2022/6/9 10:35
 */
public class AnnotationColumnWidthWriteHandler extends AbstractColumnWidthStyleStrategy {

    /**
     * {@link AnnotationColumnWidthWriteHandler#annotationExcelSourceList} 的数据个数
     */
    private final int excelSourceSize;

    /**
     * 实体类单元格样式参数配置集合
     */
    private final List<ExportLabelSource> annotationExcelSourceList;

    public AnnotationColumnWidthWriteHandler(List<ExportLabelSource> annotationExcelSourceList) {
        this.annotationExcelSourceList = annotationExcelSourceList;
        this.excelSourceSize = ObjectUtil.length(annotationExcelSourceList);
    }

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 设置行高
        cell.getRow().setHeight(isHead ? (short) 500 : (short) 350);

        int columnIndex = cell.getColumnIndex();
        if (isHead && relativeRowIndex == 0 && excelSourceSize >= columnIndex) {
            // 设置指定索引位的列宽
            writeSheetHolder.getSheet().setColumnWidth(columnIndex, annotationExcelSourceList.get(columnIndex).getColumnWidth());
        }
    }

}
